package cn.may.interceptor;

import cn.may.domain.student.Student;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author mayuanbao
 * @date 2019-06-10 9:51
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
//    private static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("登录状态拦截");
        HttpSession session = request.getSession();
        // 获取用户信息,如果没有则拦截
        Student student = (Student) session.getAttribute("student");
        System.out.println(student);
        if (student == null) {
            log.info("请登录！");
            response.setCharacterEncoding("utf-8");
            response.getWriter().write("请登录！");
            return false;
        } else {
            log.info("已经登录，用户信息为： " + student);
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
